package com.sxx.beautifulcity.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
import com.sxx.beautifulcity.R;
import com.sxx.beautifulcity.application.ProjectApplication;
import com.sxx.beautifulcity.database.LoginUserHelper;
import com.sxx.beautifulcity.database.UserHelper;
import com.sxx.beautifulcity.dialog.CommonProgressDialog;
import com.sxx.beautifulcity.entity.greendao.LoginUserDaoEntity;
import com.sxx.beautifulcity.entity.greendao.UserDaoEntity;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by dllo on 15/10/21.
 */
public class LoginActivity extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private EditText accounNumberEt, paw;
    private ImageButton showPswIv;
    private CheckBox checkBox;
    private Button loginBtn;
    private UserHelper helper;
    private TextView findPswTv, shadow;
    private int size = 0;//点击显示密码图标的次数
    private SharedPreferences sp;
    private Effectstype effect;
    private LoginUserHelper userHelper;

    private TextView freeRegisterTv, sinaTv, weiixnTv, qqTv;
    private UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
    //参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
    private UMQQSsoHandler qqSsoHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        // 初始化缓存对象 访问权限为本程序 文件名称为login
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        qqSsoHandler = new UMQQSsoHandler(this, "1104869349",
                "dGD1LBSMprbe54g5");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(resultCode);

        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(resultCode, resultCode, data);
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        userHelper = new LoginUserHelper();
        helper = new UserHelper();
        accounNumberEt = (EditText) findViewById(R.id.accounNumberEt);
        paw = (EditText) findViewById(R.id.paw);
        showPswIv = (ImageButton) findViewById(R.id.showPswIv);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        loginBtn = (Button) findViewById(R.id.loginBtn);
        freeRegisterTv = (TextView) findViewById(R.id.freeRegisterTv);
        sinaTv = (TextView) findViewById(R.id.sinaTv);
        weiixnTv = (TextView) findViewById(R.id.weiixnTv);
        qqTv = (TextView) findViewById(R.id.qqTv);
        findPswTv = (TextView) findViewById(R.id.findPswTv);
        shadow = (TextView) findViewById(R.id.shadow);
        // 从上到下分别是：阴影的颜色；X轴位移（水平位移）；
        // Y轴位移（垂直位移）；模糊半径。 模糊半径越大，投影效果越大。
        shadow.setShadowLayer(1F, 1F, 5F, Color.BLACK);
        showPswIv.setOnClickListener(this);
        findPswTv.setOnClickListener(this);
        weiixnTv.setOnClickListener(this);
        qqTv.setOnClickListener(this);
        sinaTv.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        checkBox.setOnCheckedChangeListener(this);
        freeRegisterTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                loginJudge();
                break;
            case R.id.sinaTv:
                sinaLogin();
                break;
            case R.id.weiixnTv:

                break;
            case R.id.qqTv:
                qqLogin();
                break;
            case R.id.showPswIv:
                size++;
                if (size % 2 == 1) {
                    paw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    paw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;
            case R.id.freeRegisterTv:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.left_out, R.anim.right_into);
                break;
            case R.id.findPswTv:
                Intent intent1 = new Intent(this, FindPawActivity.class);
                startActivity(intent1);
                finish();
                overridePendingTransition(R.anim.left_out, R.anim.right_into);
                break;
        }
    }


    /**
     * 登录判断
     */

    private void loginJudge() {
        String name = accounNumberEt.getText().toString();
        String psw = paw.getText().toString();
        String num = accounNumberEt.getText().toString();

        List<UserDaoEntity> entityList = helper.queryName(name, num);
        if (entityList != null && entityList.size() > 0) {

            if (psw.equals(entityList.get(0).getUserPsw())) {
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("name", name);
                startActivity(intent);
                finish();
                if (userHelper != null) {
                    userHelper.deleteAll();
                    List<LoginUserDaoEntity> entities = new ArrayList<>();
                    LoginUserDaoEntity daoEntity = new LoginUserDaoEntity();
                    daoEntity.setUser_login_name(name);
                    daoEntity.setUser_login_paw(psw);
                    daoEntity.setZhanghao(num);
                    entities.add(daoEntity);
                    userHelper.savaLoginUser(entities);
                }
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            isNotRegister();
        }
    }


    /**
     * 新浪登录
     */

    private void sinaLogin() {

        mController.doOauthVerify(LoginActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(Bundle bundle, SHARE_MEDIA share_media) {
                if (bundle != null && !TextUtils.isEmpty(bundle.getString("uid"))) {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                    Toast.makeText(LoginActivity.this, "授权成功.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA share_media) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {

            }
        });
        mController.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMDataListener() {
            @Override
            public void onStart() {
                Toast.makeText(LoginActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {
                if (status == 200 && info != null) {
                    StringBuilder sb = new StringBuilder();
                    Set<String> keys = info.keySet();
                    for (String key : keys) {
                        sb.append(key + "=" + info.get(key).toString() + "\r\n");
                    }
                    Log.d("TestData", sb.toString());
                } else {
                    Log.d("TestData", "发生错误：" + status);
                }
            }
        });
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
    }

    /***
     * qq登录
     */

    private void qqLogin() {

        qqSsoHandler.addToSocialSDK();
        mController.doOauthVerify(this, SHARE_MEDIA.QQ, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {

            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {

            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {

                //获取相关授权信息
                mController.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMDataListener() {
                    @Override
                    public void onStart() {
                        Toast.makeText(LoginActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            StringBuilder sb = new StringBuilder();
                            Set<String> keys = info.keySet();
                            for (String key : keys) {
                                sb.append(key + "=" + info.get(key).toString() + "\r\n");
                            }
                            Log.d("TestData", sb.toString());
                        } else {
                            Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {

            }
        });
    }

    /**
     * 还未注册不能登录
     **/
    private void isNotRegister() {
        final NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(this);
        dialogBuilder
                .withTitle(null)
                .withTitleColor("#FFFFFF")
                .withDividerColor("#f3aece")
                .withMessage("您还未注册,请先注册")
                .withMessageColor("#FFFFFFFF")
                .withDialogColor("#f3aece")
                .withIcon(getResources().getDrawable(R.mipmap.ic_launcher))
                .isCancelableOnTouchOutside(true)
                .withDuration(700)
                .withEffect(effect)
                .withButton1Text("去注册")
                .withButton2Text("取消")
                .setButton1Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(LoginActivity.this, RegisterActivity.class);
                        startActivity(intent);
                        finish();
                    }
                })
                .setButton2Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogBuilder.dismiss();
                    }
                });
        dialogBuilder.show();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 保存自动登录的选中状态
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("isAutoLogin", isChecked);
        editor.commit();// 提交
    }
}
